package drive.Mapper;

import drive.Model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Insert("INSERT INTO user(username, password, email, creditScore, createTime, status, headshot) VALUES(#{username}, #{password}, #{email}, #{creditScore}, #{createTime}, #{status}, #{headshot})")
    @Options(useGeneratedKeys = true, keyProperty = "userID")
    int insertUser(User user);

    // 根据ID读取用户
    @Select("SELECT * FROM user WHERE userID = #{userID}")
    User selectUserById(int userID);

    // 查询所有用户
    @Select("SELECT * FROM user")
    List<User> selectAllUsers();

    // 更新用户
    @Update("UPDATE user SET username = #{username}, password = #{password}, email = #{email}, headshot = #{headshot} WHERE userID = ${userID}")
    int updateUser(User user);

    // 删除用户
    @Delete("DELETE FROM user WHERE userID = #{userID}")
    int deleteUser(int userID);

    // 根据用户名查询用户
    @Select("SELECT * FROM user WHERE username = #{username}")
    User selectUserByUsername(String username);

    // 根据邮箱查询用户
    @Select("SELECT * FROM user WHERE email = #{email}")
    User selectUserByEmail(String email);

    // 根据用户名和密码查询用户
    @Select("SELECT * FROM user WHERE username = #{username} AND password = #{password}")
    User selectUserByUsernameAndPassword(String username, String password);

    /**
     * 根据用户ID列表获取用户信息（分页）
     * @param userIds 用户ID列表
     * @param offset 偏移量
     * @param pageSize 每页大小
     * @return 用户信息列表
     */
    @Select("<script>" +
            "SELECT * FROM user " +
            "WHERE userID IN " +
            "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>#{id}</foreach> " +
            "LIMIT #{offset}, #{pageSize}" +
            "</script>")
    List<User> getUsersByIDs(List<Integer> userIds, int offset, int pageSize);

    /**
     * 根据用户ID列表获取用户总数
     * @param userIds 用户ID列表
     * @return 用户总数
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM user " +
            "WHERE userID IN " +
            "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>#{id}</foreach>" +
            "</script>")
    int getUserCountByIDs(List<Integer> userIds);

    @Update("UPDATE user SET status = 'temporaryBan' WHERE userID = #{userID}")
    void ban_user(int userID);

    /**
     * 分页获取用户列表
     * @param offset 偏移量
     * @param pageSize 每页大小
     * @return 用户列表
     */
    @Select("SELECT * FROM user LIMIT #{offset}, #{pageSize}")
    List<User> getUsers(int offset, int pageSize);

    /**
     * 获取用户总数
     * @return 用户总数
     */
    @Select("SELECT COUNT(*) FROM user")
    int getUserCount();
}
